<?php


namespace app\index\validate;


use think\Validate;

class Purchase extends Validate
{
    protected $rule = [
        ['cn_name','require','中文商品名不能为空'],
        ['en_name','require','英文商品名不能为空'],
        ['type','require|number','类型不能为空'],
        ['pur_price','require|number','单价不能为空|单价必须为数字'],
        ['amount','require|number','数量不能为空|数量必须为数字'],
        ['weight','requireIf:type,1|number','重量不能为空|重量必须为数字'],
        ['warehouse','require','仓库不能为空'],
        ['company','require','供应商不能为空'],
        ['vendor','require','供应商不能为空'],
        ['waybill_no','require','运单号不能为空'],
        ['real_pur_amount','require','实采数量不能为空'],
        ['real_pur_price','require','实采价格不能为空'],
        ['selling_price','require|number','定价不能为空|定价必须为数字'],
        ['purchase','require|array|checkPurchase:(input:\'purchase\')','采购信息必填|采购信息必须为数组|采购信息不能为空'],
        ['purchase_detail','require|array|checkPurchaseDetail:(input:\'purchase_detail\')','采购信息必填|采购信息必须为数组|采购信息不能为空'],
    ];

    protected $scene = [
        'create'  =>  ['id','cn_name','en_name','pur_price','type','amount','warehouse','company'],
        'stock_in'=>['cn_name','en_name','type','pur_price','amount','warehouse','weight','selling_price'],
        'create_batch_purchase'=>['company','purchase'],
        'purchase'=>['cn_name','en_name','type','pur_price','amount'],
        'create_batch_purchase_detail'=>['vendor','purchase_detail','waybill_no'],
        'purchase_detail'=>['amount','pur_price'],
    ];

    protected function checkPurchase($value){
        foreach ($value as $key=>$item) {
            if(!is_array($item)){
                return false;
            }
            $data=[];
            foreach ($item as $i=>$val) {
                $data[$i] = $val;
            }
            if (false === $this->scene('purchase')->check($data)) {
                return $this->getError();
            }
        }
        return true;
    }

    protected function checkPurchaseDetail($value){
        foreach ($value as $key=>$item) {
            if(!is_array($item)){
                return false;
            }
            $data=[];
            foreach ($item as $i=>$val) {
                $data[$i] = $val;
            }
            if (false === $this->scene('purchase_detail')->check($data)) {
                return $this->getError();
            }
        }
        return true;
    }
}